#include "inc/zg291bora_para.h"
#include "ui_zg291bora_para.h"

ZG291BORA_para::ZG291BORA_para(QSerialPort *serialPort,QTimer *m_timer,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ZG291BORA_para),
    serialPort(serialPort),
    m_timer(m_timer)
{
    ui->setupUi(this);
}

ZG291BORA_para::~ZG291BORA_para()
{
    delete ui;
}

void ZG291BORA_para::on_pushButton_clicked() // 读取参数按钮
{
    // 停止定时器（如果有）
    if (m_timer && m_timer->isActive()) {
        m_timer->stop();
    }

    // 检查串口状态
    if (!serialPort || !serialPort->isOpen()) {
        qDebug() << "Serial port not ready!";
        // if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第一条指令：读取0x52-0x5B寄存器 (10个寄存器) ****************/
    QByteArray request1;
    request1.append(static_cast<char>(0x00));     // 从机地址
    request1.append(static_cast<char>(0x03));     // 功能码
    request1.append(static_cast<char>(0x00));     // 起始地址高字节
    request1.append(static_cast<char>(0x52));     // 起始地址低字节 (0x52)
    request1.append(static_cast<char>(0x00));     // 寄存器数高字节
    request1.append(static_cast<char>(0x0A));     // 寄存器数低字节 (10个寄存器)

    // 计算并附加CRC
    quint16 crc1 = calculateCRC(request1);
    request1.append(static_cast<char>(crc1 & 0xFF));
    request1.append(static_cast<char>((crc1 >> 8) & 0xFF));

    // 发送第一条指令
    if (serialPort->write(request1) == -1) {
        qDebug() << "Write failed (1):" << serialPort->errorString();
        // if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第一条响应
    QByteArray response1;
    if (serialPort->waitForReadyRead(1000)) {
        response1 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response1 += serialPort->readAll();
        }
    } else {
        qDebug() << "Read timeout (1)";
        // if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第二条指令：读取0x8A-0x8B寄存器 (2个寄存器) ****************/
    QByteArray request2;
    request2.append(static_cast<char>(0x00));     // 从机地址
    request2.append(static_cast<char>(0x03));     // 功能码
    request2.append(static_cast<char>(0x00));     // 起始地址高字节
    request2.append(static_cast<char>(0x8A));     // 起始地址低字节 (0x8A)
    request2.append(static_cast<char>(0x00));     // 寄存器数高字节
    request2.append(static_cast<char>(0x02));     // 寄存器数低字节 (2个寄存器)

    // 计算并附加CRC
    quint16 crc2 = calculateCRC(request2);
    request2.append(static_cast<char>(crc2 & 0xFF));
    request2.append(static_cast<char>((crc2 >> 8) & 0xFF));

    // 发送第二条指令
    if (serialPort->write(request2) == -1) {
        qDebug() << "Write failed (2):" << serialPort->errorString();
        // if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第二条响应
    QByteArray response2;
    if (serialPort->waitForReadyRead(1000)) {
        response2 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response2 += serialPort->readAll();
        }
    } else {
        qDebug() << "Read timeout (2)";
        // if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 解析响应数据并更新UI ****************/

    // 解析第一条响应 (0x52-0x5B) - 10个寄存器
    if (response1.size() >= 23) {  // 10寄存器×2 + 5字节头尾
        // 寄存器0x52: 大气压报警上限
        quint16 BORA_UP = (static_cast<quint8>(response1[3]) << 8) | static_cast<quint8>(response1[4]);
        ui->bord_up->setText(QString::number(BORA_UP/100.0,'f',2));

        // 寄存器0x53: 大气压报警上限回差
        quint16 BORA_UPDEFF = (static_cast<quint8>(response1[5]) << 8) | static_cast<quint8>(response1[6]);
        ui->bordup_deff->setText(QString::number(BORA_UPDEFF/100.0,'f',2));

        // 寄存器0x54: 大气压报警上限继电器
        quint16 BORA_UPRELAY = (static_cast<quint8>(response1[7]) << 8) | static_cast<quint8>(response1[8]);
        ui->bord_uprelay->setCurrentIndex(BORA_UPRELAY);

        // 寄存器0x55: 大气压报警下限
        quint16 BORA_DOWN = (static_cast<quint8>(response1[9]) << 8) | static_cast<quint8>(response1[10]);
        ui->bord_down->setText(QString::number(BORA_DOWN/100.0,'f',2));

        // 寄存器0x56: 大气压报警下限回差
        quint16 BORA_DOWNDEFF = (static_cast<quint8>(response1[11]) << 8) | static_cast<quint8>(response1[12]);
        ui->bord_downdeff->setText(QString::number(BORA_DOWNDEFF/100.0,'f',2));

        // 寄存器0x57: 大气压报警下限继电器
        quint16 BORA_DOWNRELAY = (static_cast<quint8>(response1[13]) << 8) | static_cast<quint8>(response1[14]);
        ui->bord_downrelay->setCurrentIndex(BORA_DOWNRELAY);

        // 寄存器0x58: 大气压预警上限
        quint16 BORA_UPWARNING = (static_cast<quint8>(response1[15]) << 8) | static_cast<quint8>(response1[16]);
        ui->bord_upwarning->setText(QString::number(BORA_UPWARNING/100.0,'f',2));

        // 寄存器0x59: 大气压预警上限开关
        quint16 BORA_UPWARNING_EN = (static_cast<quint8>(response1[17]) << 8) | static_cast<quint8>(response1[18]);
        ui->bord_warning_en->setCurrentIndex(BORA_UPWARNING_EN);

        // 寄存器0x5A: 大气压预警下限
        quint16 BORA_DOWNWARNING = (static_cast<quint8>(response1[19]) << 8) | static_cast<quint8>(response1[20]);
        ui->bord_downwarning->setText(QString::number(BORA_DOWNWARNING/100.0,'f',2));

        // 寄存器0x5B: 大气压预警下限开关
        quint16 BORA_DOWNWARNING_EN = (static_cast<quint8>(response1[21]) << 8) | static_cast<quint8>(response1[22]);
        ui->bord_downwarning_en->setCurrentIndex(BORA_DOWNWARNING_EN);
    } else {
        qDebug() << "Invalid response1 length:" << response1.size();
    }

    // 解析第二条响应 (0x8A-0x8B) - 2个寄存器
    if (response2.size() >= 7) {  // 2寄存器×2 + 5字节头尾
        // 寄存器0x8A: 大气压校准系数
        qint16 BORAK = (static_cast<quint8>(response2[3]) << 8) | static_cast<quint8>(response2[4]);
        ui->borbK->setText(QString::number(BORAK/10.0,'f',1));

        // 寄存器0x8B: 大气压偏移修正
        quint16 BORAB = (static_cast<quint8>(response2[5]) << 8) | static_cast<quint8>(response2[6]);
        ui->bordB->setText(QString::number(BORAB/100.0,'f',3));
    } else {
        qDebug() << "Invalid response2 length:" << response2.size();
    }

    // 恢复定时器（如果有）
    // if (m_timer) m_timer->start(2000);
}

void ZG291BORA_para::on_pushButton_2_clicked() // 设置参数按钮
{
    // 停止定时器（如果有）
    if (m_timer && m_timer->isActive()) {
        m_timer->stop();
    }

    // 检查串口状态
    if (!serialPort || !serialPort->isOpen()) {
        qDebug() << "Serial port not ready!";
        // if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第一条指令：写入0x52-0x5B寄存器 (10个寄存器) ****************/
    QByteArray request1;
    request1.append(static_cast<char>(0x00));     // 从机地址
    request1.append(static_cast<char>(0x10));     // 功能码(写多个寄存器)
    request1.append(static_cast<char>(0x00));     // 起始地址高字节
    request1.append(static_cast<char>(0x52));     // 起始地址低字节 (0x52)
    request1.append(static_cast<char>(0x00));     // 寄存器数高字节
    request1.append(static_cast<char>(0x0A));     // 寄存器数低字节 (10个寄存器)
    request1.append(static_cast<char>(0x14));     // 字节数 (10寄存器×2=20字节)

    // 添加寄存器值
    float bora_up = ui->bord_up->text().toFloat();
    short bora_up_int = static_cast<short>(bora_up * 100);
    request1.append(static_cast<char>(bora_up_int >> 8));
    request1.append(static_cast<char>(bora_up_int & 0xFF));

    float bora_updeff = ui->bordup_deff->text().toFloat();
    short bora_updeff_int = static_cast<short>(bora_updeff * 100);
    request1.append(static_cast<char>(bora_updeff_int >> 8));
    request1.append(static_cast<char>(bora_updeff_int & 0xFF));

    request1.append(static_cast<char>(ui->bord_uprelay->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->bord_uprelay->currentIndex() & 0xFF));

    float bora_down = ui->bord_down->text().toFloat();
    short bora_down_int = static_cast<short>(bora_down * 100);
    request1.append(static_cast<char>(bora_down_int >> 8));
    request1.append(static_cast<char>(bora_down_int & 0xFF));

    float bora_downdeff = ui->bord_downdeff->text().toFloat();
    short bora_downdeff_int = static_cast<short>(bora_downdeff * 100);
    request1.append(static_cast<char>(bora_downdeff_int >> 8));
    request1.append(static_cast<char>(bora_downdeff_int & 0xFF));

    request1.append(static_cast<char>(ui->bord_downrelay->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->bord_downrelay->currentIndex() & 0xFF));

    float bora_upwarning = ui->bord_upwarning->text().toFloat();
    short bora_upwarning_int = static_cast<short>(bora_upwarning * 100);
    request1.append(static_cast<char>(bora_upwarning_int >> 8));
    request1.append(static_cast<char>(bora_upwarning_int & 0xFF));

    request1.append(static_cast<char>(ui->bord_warning_en->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->bord_warning_en->currentIndex() & 0xFF));

    float bora_downwarning = ui->bord_downwarning->text().toFloat();
    short bora_downwarning_int = static_cast<short>(bora_downwarning * 100);
    request1.append(static_cast<char>(bora_downwarning_int >> 8));
    request1.append(static_cast<char>(bora_downwarning_int & 0xFF));

    request1.append(static_cast<char>(ui->bord_downwarning_en->currentIndex() >> 8));
    request1.append(static_cast<char>(ui->bord_downwarning_en->currentIndex() & 0xFF));

    // 计算并附加CRC
    quint16 crc1 = calculateCRC(request1);
    request1.append(static_cast<char>(crc1 & 0xFF));
    request1.append(static_cast<char>((crc1 >> 8) & 0xFF));

    // 发送第一条指令
    if (serialPort->write(request1) == -1) {
        qDebug() << "Write failed (1):" << serialPort->errorString();
        // if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第一条响应
    QByteArray response1;
    if (serialPort->waitForReadyRead(1000)) {
        response1 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response1 += serialPort->readAll();
        }
    } else {
        qDebug() << "Write response timeout (1)";
        // if (m_timer) m_timer->start(2000);
        return;
    }

    /**************** 第二条指令：写入0x8A-0x8B寄存器 (2个寄存器) ****************/
    QByteArray request2;
    request2.append(static_cast<char>(0x00));     // 从机地址
    request2.append(static_cast<char>(0x10));     // 功能码(写多个寄存器)
    request2.append(static_cast<char>(0x00));     // 起始地址高字节
    request2.append(static_cast<char>(0x8A));     // 起始地址低字节 (0x8A)
    request2.append(static_cast<char>(0x00));     // 寄存器数高字节
    request2.append(static_cast<char>(0x02));     // 寄存器数低字节 (2个寄存器)
    request2.append(static_cast<char>(0x04));     // 字节数 (2寄存器×2=4字节)

    // 处理浮点数校准系数
    float BORAK_float = ui->borbK->text().toFloat();
    short BORAK_int = static_cast<short>(BORAK_float * 10);

    request2.append(static_cast<char>(BORAK_int >> 8));
    request2.append(static_cast<char>(BORAK_int & 0xFF));

    float BORAB_float = ui->bordB->text().toFloat();
    short BORAB_int = static_cast<short>(BORAB_float * 100);
    request2.append(static_cast<char>(BORAB_int >> 8));
    request2.append(static_cast<char>(BORAB_int & 0xFF));

    // 计算并附加CRC
    quint16 crc2 = calculateCRC(request2);
    request2.append(static_cast<char>(crc2 & 0xFF));
    request2.append(static_cast<char>((crc2 >> 8) & 0xFF));

    // 发送第二条指令
    if (serialPort->write(request2) == -1) {
        qDebug() << "Write failed (2):" << serialPort->errorString();
        // if (m_timer) m_timer->start(2000);
        return;
    }

    // 读取第二条响应
    QByteArray response2;
    if (serialPort->waitForReadyRead(1000)) {
        response2 = serialPort->readAll();
        while (serialPort->waitForReadyRead(100)) {
            response2 += serialPort->readAll();
        }
    } else {
        qDebug() << "Write response timeout (2)";
        // if (m_timer) m_timer->start(2000);
        return;
    }

    // 恢复定时器（如果有）
    // if (m_timer) m_timer->start(2000);

    qDebug() << "BORA Parameters set successfully";
}

